import { ElMessage } from 'element-plus'
import router from '@/router'
import { useCache } from '@/hooks/web/useCache'

const { wsCache } = useCache()

const logout = () => {
  router.push('/home')
}

const NetErrorHooks = {
  403: logout,
  401: logout
}

export const onRequest = (config) => {
  const useStore = {
    isLogin: true
  }
  if (!config.headers) {
    config.headers = {}
  }
  if (useStore.isLogin) {
    config.headers.token = wsCache.get('Admin-Token')
  }

  return config
}

export const onResponse = (config) => {
  console.log('config', config)
  const { error_code, error_msg } = config.data || {}
  if (error_code === 200) {
    return Promise.resolve(config.data)
  } else {
    if (NetErrorHooks[error_code]) {
      NetErrorHooks[error_code](config)
      router.push('/home')
    }
    const error = new Error(error_msg)
    error.data = config
    if (config.disabledToast !== true) {
      ElMessage.error(error_msg)
    }
    // router.push('/home')
    return Promise.reject(error)
  }
}

export const onRequestRejected = (error) => {
  return Promise.reject(error)
}

export const onResponseRejected = (err) => {
  const { config, response, isAxiosError } = err || {}
  if (isAxiosError) {
    const { status } = response || {}
    if (NetErrorHooks[status]) {
      NetErrorHooks[status](config)
    }
    if (config.disabledToast !== true) {
      ElMessage.error(err.message)
    }
    return Promise.reject(err)
  } else {
    ElMessage.error(err.message)
    return Promise.reject(err)
  }
}
